package com.agent;

import com.interceptor.DelegateLogic;

import net.bytebuddy.agent.builder.AgentBuilder;
import net.bytebuddy.implementation.MethodDelegation;
import net.bytebuddy.matcher.ElementMatchers;

import java.lang.instrument.Instrumentation;

public class T_04_DelegateAgent {

    public static void premain(String args, Instrumentation inst) {
        System.out.println("agent=========T_04_DelegateAgent.premain()");
        install(inst);
    }

    public static void agentmain(String args, Instrumentation inst) {
        System.out.println("agent=========T_04_DelegateAgent.agentmain");
        install(inst);
    }

    private static void install(Instrumentation inst) {
        new AgentBuilder.Default()
                //.with(AgentBuilder.Listener.StreamWriting.toSystemOut())
                .type(ElementMatchers.named("com.test.Aa"))
                .transform((builder, td, cl, m) -> {
                            System.out.println("agent=========T_04_DelegateAgent.install()");
                            return builder.method(ElementMatchers.named("createAa")
                                    )
                                    .intercept(MethodDelegation.to(DelegateLogic.class));
                        }
                )
                .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)
                .installOn(inst);
    }


}